package com.wu.util;

import org.apache.commons.lang3.StringEscapeUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

/**
 * @ClassName BaseUtil
 * @Author wuxuan
 * @Date 2019/2/17 20:52
 * @Version 1.0
 * @Description
 **/
public class BaseUtil {
    private static BaseUtil util;

    private BaseUtil() {
    }

    public static BaseUtil getUtil() {
        if (util == null) {
            util = new BaseUtil();
        }
        return util;
    }

    public String doPost(String httpUrl, String param, String method) {

        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接请求方式
            connection.setRequestMethod(method);
            // 设置连接主机服务器超时时间：15000毫秒
            connection.setConnectTimeout(10000);
            // 设置读取主机服务器返回数据超时时间：60000毫秒
            connection.setReadTimeout(20000);
            // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
            connection.setDoOutput(true);
            // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
            connection.setDoInput(true);
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 通过连接对象获取一个输出流
            os = connection.getOutputStream();
            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
            os.write(param.getBytes());
            // 通过连接对象获取一个输入流，向远程读取
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            connection.disconnect();
        }
        return result;
    }

    public String getParm(Map parm){
        /**
         *@MethodName getParm
         *@Data 2019/2/17 21:17
         *@Author wuxuan
         *@Description map转kay=value&key=value型字符
         **/
        return parm.toString().replace("{","").replace("}","").replace(", ","&");
    }
    public String quZhuanYi(String str){
        /**
         *@MethodName quZhuanYi
         *@Data 2019/2/17 21:19
         *@Author wuxuan
         *@Description 去转译符号
         **/
        return StringEscapeUtils.unescapeEcmaScript(str);
    }
    public String getFormartTime(String formart){
        /**
         *@MethodName getFormartTime
         *@Data 2019/3/2 18:20
         *@Author wuxuan
         *@Description  获取格式化的时间 默认 yyyy/MM/dd HH:mm:ss格式
         **/
        SimpleDateFormat dateFormat=null;
        if (formart == null) {
            dateFormat =new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        }else {
            dateFormat =new SimpleDateFormat(formart);
        }
        return dateFormat.format(new Date());
    }
    public String getLongTime(){
        /**
         *@MethodName getLongTime
         *@Data 2019/3/2 18:16
         *@Author wuxuan
         *@Description 获取整形时间 yyyyMMddHHmmss格式
         **/
        SimpleDateFormat formats=new SimpleDateFormat("yyyyMMddHHmmss");
        return formats.format(new Date());
    }
    public String getIpAddress(HttpServletRequest request) {
        /**
         *@MethodName getIpAddress
         *@Data 2019/3/2 19:26
         *@Author wuxuan
         *@Description 获取请求的ip
         **/
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.contains(",")) {
            return ip.split(",")[0];
        } else {
            return ip;
        }
    }
    public String getUUID(){
        /**
         *@MethodName getUUID
         *@Data 2019/3/2 20:11
         *@Author wuxuan
         *@Description 获取UUID
         **/
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
    public String getRoundNum(int max,int min){
        /**
         *@MethodName getRoundNum
         *@Data 2019/3/3 20:55
         *@Author wuxuan
         *@Description 获取随机数
         **/
        Random random = new Random();
        int s = random.nextInt(max) % (max - min + 1) + min;
        return String.valueOf(s);
    }
    public String GBKtoUTF8(String sourceString) {
        String resultString=null;
        try {
            resultString= new String(sourceString.getBytes("GBK"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return resultString;
    }
    public String ISOtoUtd8(String sourceString){
        String resultString=null;
        try {
            resultString=new String(sourceString.getBytes("iso-8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return resultString;
    }
}

